<template>
  <div ref="map3" id="map3">
    <!-- 图层 -->
    <div id="alllayers" position="top-left" style="display: block; overflow: auto" v-if="isShow === '1'">
      <a-tree
        v-model="checkedKeys"
        checkable
        :default-expand-all="true"
        :auto-expand-parent="autoExpandParent"
        :selected-keys="selectedKeys"
        :tree-data="treeData"
        @expand="onExpand"
        @select="onSelect"
        @check="onCheck"
      />
    </div>
    <!-- 显示经纬度、高度 -->
    <div>
      <div class="mywindow" id="windowbox" position="bottom-left"></div>
    </div>

    <!-- 切换底图 -->
    <div class="myearth" id="earth" position="bottom-right">
      <a href="#" @click="changeEarth('img')">
        <img src="/static/img_c.png" alt="图片不见了" style="width: 100px; height: 100px" />
        <div>卫星底图</div>
      </a>
      <a href="#" @click="changeEarth('vec')">
        <img src="/static/vec_c.png" alt="图片不见了" style="width: 100px; height: 100px; margin-left: 8px" />
        <div>矢量底图</div>
      </a>
    </div>
    <!-- 飞行 -->
    <div id="toolbar" class="fly" v-if="isShow === '3'" position="top-left">
      <a type="button" class="button" @click="startFly">开始</a>
      <a type="button" class="button" @click="pauseFly">暂停</a>
      <a type="button" class="button" @click="stopFly">停止</a>
      <div style="width: 150px">
        <a type="button" class="button" @click="addPlace">添加站点</a>
        <a type="button" class="button" @click="cleanPlace">清除站点</a>
      </div>
      <div class="checkbox">
        <label> <input type="checkbox" id="show-line" checked @change="changeLine" /> 显示站点和路线 </label>
      </div>
    </div>
    <!-- 漫游 -->
    <div id="manyou" class="fly" v-if="isShow === '5'" position="top-left">
      <div style="width: 160px">
        <a type="button" class="button" @click="freeden">开启漫游</a>
        <a type="button" @click="quit" class="button">退出漫游</a>
        <a type="button" @click="creatmycar" class="button" v-if="hideCar === 1">第三人称漫游</a>
        <a type="button" @click="controlCar" class="button" v-else-if="hideCar === 2">确定</a>
        <div>
          提示：镜头通过WASD控制前后左右的方向，QE控制升降，鼠标单击后滑动可控制视角；
          <br />
          小人通过上下左右键控制
        </div>
      </div>
    </div>
    <!-- 弹窗 -->
    
    <div id="bubble" class="bubble" style="bottom:0;left:82%;display:none;" v-show="showBuble" >
        <div id="tools" style="text-align : right">
        <span  style="color: rgb(95, 74, 121);padding: 5px;position: absolute;left: 10px;top: 4px;">对象属性</span>
        <!-- <span class="fui-export" id="bubblePosition" style="color: darkgrey; padding:5px" title="停靠"></span> -->
        <span  class="fui-cross" @click="closebubble" title="关闭" id="close" style="color: darkgrey;padding:5px"></span>
        </div>
    <div style="overflow-y:scroll;height:150px" id="tableContainer"><table id="tab"></table></div>
    </div> 
    <sm-viewer>
      <!-- 量测 -->
      <sm3d-measure></sm3d-measure>
      <!-- 阴影分析 -->
      <sm3d-shadowquery></sm3d-shadowquery>
      <!-- 裁剪cross -->
      <sm3d-clip-cross></sm3d-clip-cross>
    </sm-viewer>
  </div>
</template>

<script>
//添加白模
    // var tileset = viewer.scene.primitives.add(
    //   new Cesium.Cesium3DTileset({
    //     url: '/static/build3dtiles/tileset.json',
    //     // url: 'http://data.marsgis.cn/3dtiles/qx-changfang/tileset.json'
    //   })
    // )
    // viewer.scene.primitives.add(tileset)
    // tileset.readyPromise.then(function (tileset) {
    //   viewer.scene.primitives.add(tileset)
    //   var heightOffset = 500.0 //高度
    //   var boundingSphere = tileset.boundingSphere

    //   //Cesium.Cartographic.fromCartesian (cartesian, ellipsoid , result )
    //   var cartographic = Cesium.Cartographic.fromCartesian(boundingSphere.center)
    //   var surface = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, cartographic.height)

    //   //Cesium.Cartesian3.fromRadians (longitude, latitude, height , ellipsoid , result )
    //   var offset = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, heightOffset)

    //   //Cesium.Cartesian3.subtract (left, right, result)
    //   var translation = Cesium.Cartesian3.subtract(offset, surface, new Cesium.Cartesian3())
    //   tileset.modelMatrix = Cesium.Matrix4.fromTranslation(translation)
    //   viewer.zoomTo(tileset, new Cesium.HeadingPitchRange(0.5, -0.2, tileset.boundingSphere.radius * 1.0))
    // })
import '@supermap/vue-iclient3d-webgl/dist/styles/vue-iclient3d-webgl.min.css'
import screenfull from 'screenfull'

var tcObj = {}
var myChildren = []

export default {
  name: 'show3D',
  data() {
    return {
      //自动展开父节点--
      autoExpandParent: true,
      checkedKeys: [],
      selectedKeys: [],
      mylist: undefined,
      treeData: [
        {
          title: '图层',
          key: '图层',
          children: [],
        },
      ],
      isShow: '',
      choosedname: '',
      allStops: [],
      toStartFly: '',
      drowallStops: [],
      line_bool: true,
      index: undefined,
      copyIndex: undefined,
      down: undefined,
      up: undefined,
      hideCar: 1,
      showBuble: false,
    }
  },
  methods: {
    closebubble() {
      this.showBuble = false
    },
    createBubble(arr,obj) {
      this.showBuble = true
      console.log(arr)
      console.log(obj);
      var table = document.getElementById("tab");
      for (var i = table.rows.length-1;i > -1;i--){
                table.deleteRow(i);
            }
      for(var index in obj){
                var newRow = table.insertRow();
                var cell1 = newRow.insertCell();
                var cell2 = newRow.insertCell();
                cell1.innerHTML = index;
                cell2.innerHTML = obj[index];
            }
      // var table = document.getElementById("tab");
      // for(var index in arr){
      //           var newRow = table.insertRow();
      //           var cell1 = newRow.insertCell();
      //           var cell2 = newRow.insertCell();
      //           cell1.innerHTML = arr[index];
      //           cell2.innerHTML = arr[index];
      //       }
    },
    // 切换底图
    changeEarth(val) {
      var imageryLayers = viewer.imageryLayers
      // imageryLayers.colorToAlpha = Cesium.Color.BLUE
      if (val === 'img') {
        var baseLayer = imageryLayers.get(1)
        var labelImagery = new Cesium.TiandituImageryProvider({
          mapStyle: Cesium.TiandituMapsStyle.IMG_C,
          token: '9a070d5592c8fcc4fa1ef70a49723f68',
        })
        // labelImagery.defaultAlpha=0.8
        // labelImagery.defaultHue=0.8

        imageryLayers.addImageryProvider(labelImagery)
        imageryLayers.remove(baseLayer)
      } else {
        var baseLayer = imageryLayers.get(1)
        var labelImagery = new Cesium.TiandituImageryProvider({
          mapStyle: Cesium.TiandituMapsStyle.VEC_C,
          token: '9a070d5592c8fcc4fa1ef70a49723f68',
        })
        imageryLayers.addImageryProvider(labelImagery)
        imageryLayers.remove(baseLayer)
      }
      var CIA = new Cesium.TiandituImageryProvider({
        mapStyle: Cesium.TiandituMapsStyle.CIA_C, //VEC_C矢量地图cva_c
        token: '9a070d5592c8fcc4fa1ef70a49723f68',
      })
      imageryLayers.addImageryProvider(CIA)
    },
    // 退出漫游
    quit() {
      viewer.trackedEntity = ''
      scene.screenSpaceCameraController.enableRotate = true
      scene.screenSpaceCameraController.enableTranslate = true
      scene.screenSpaceCameraController.enableZoom = true
      scene.screenSpaceCameraController.enableTilt = true
      scene.screenSpaceCameraController.enableLook = true
      viewer.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOWN)
      viewer.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE)
      viewer.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_UP)
      document.removeEventListener('keydown', this.down, false)
      document.removeEventListener('keyup', this.up, false)
    },
    // 自由镜头or漫游
    freeden() {
      // this.e()
      var ellipsoid = viewer.scene.globe.ellipsoid

      scene.screenSpaceCameraController.enableRotate = false
      scene.screenSpaceCameraController.enableTranslate = false
      scene.screenSpaceCameraController.enableZoom = false
      scene.screenSpaceCameraController.enableTilt = false
      scene.screenSpaceCameraController.enableLook = false

      var startMousePosition
      var mousePosition
      var flags = {
        looking: false,
        moveForward: false,
        moveBackward: false,
        moveUp: false,
        moveDown: false,
        moveLeft: false,
        moveRight: false,
      }

      viewer.screenSpaceEventHandler.setInputAction(function (movement) {
        flags.looking = true
        mousePosition = startMousePosition = Cesium.Cartesian3.clone(movement.position)
      }, Cesium.ScreenSpaceEventType.LEFT_DOWN)

      viewer.screenSpaceEventHandler.setInputAction(function (movement) {
        mousePosition = movement.endPosition
      }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)

      viewer.screenSpaceEventHandler.setInputAction(function (position) {
        flags.looking = false
      }, Cesium.ScreenSpaceEventType.LEFT_UP)

      function getFlagForKeyCode(keyCode) {
        switch (keyCode) {
          case 'W'.charCodeAt(0):
            return 'moveForward'
          case 'S'.charCodeAt(0):
            return 'moveBackward'
          case 'Q'.charCodeAt(0):
            return 'moveUp'
          case 'E'.charCodeAt(0):
            return 'moveDown'
          case 'D'.charCodeAt(0):
            return 'moveRight'
          case 'A'.charCodeAt(0):
            return 'moveLeft'
          default:
            return undefined
        }
      }

      document.addEventListener(
        'keydown',
        (this.down = function (e) {
          var flagName = getFlagForKeyCode(e.keyCode)
          if (typeof flagName !== 'undefined') {
            flags[flagName] = true
          }
        }),
        false
      )

      document.addEventListener(
        'keyup',
        (this.up = (e) => {
          var flagName = getFlagForKeyCode(e.keyCode)
          if (typeof flagName !== 'undefined') {
            flags[flagName] = false
          }
        }),
        false
      )

      viewer.clock.onTick.addEventListener(function (clock) {
        var camera = viewer.camera
        // 镜头旋转
        if (flags.looking) {
          var width = viewer.canvas.clientWidth
          var height = viewer.canvas.clientHeight

          var lookFactor = 0.06
          var x = (mousePosition.x - startMousePosition.x) / width
          var y = -(mousePosition.y - startMousePosition.y) / height

          camera.setView({
            // position:Cesium.Cartesian3.fromDegrees(109.49404611080851,18.2966550140225,12.0),
            orientation: {
              heading: camera.heading + x * lookFactor,
              pitch: camera.pitch + y * lookFactor,
              roll: 0.0,
            },
          })
        }

        // 根据高度来决定镜头移动的速度
        var cameraHeight = ellipsoid.cartesianToCartographic(camera.position).height
        var moveRate = cameraHeight / 100.0

        if (flags.moveForward) {
          camera.moveForward(moveRate)
        }
        if (flags.moveBackward) {
          camera.moveBackward(moveRate)
        }
        if (flags.moveUp) {
          camera.moveUp(moveRate)
        }
        if (flags.moveDown) {
          camera.moveDown(moveRate)
        }
        if (flags.moveLeft) {
          camera.moveLeft(moveRate)
        }
        if (flags.moveRight) {
          camera.moveRight(moveRate)
        }
      })
    },
    // 控制小车
    creatmycar() {
      this.$notification.open({
        message: `提示`,
        description: '接下来请在地图上选择一个点,然后点击左边的确定按钮',
      })
      this.hideCar = 2
    },
    controlCar() {
      let str = document.getElementById('windowbox').innerHTML.toString().split('&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;')
      let newStr = [parseFloat(str[0].substring(3)), parseFloat(str[1].substring(3)), parseFloat(str[2].substring(3))]
      // 小车旋转角度
      let radian = Cesium.Math.toRadians(2.0)
      // 小车的速度
      let speed = 0.15
      // 速度矢量
      let speedVector = new Cesium.Cartesian3()
      let scene = viewer.scene
      // 起始位置
      let position = Cesium.Cartesian3.fromDegrees(newStr[0], newStr[1], newStr[2])
      // 用于设置小车方向
      let hpRoll = new Cesium.HeadingPitchRoll()
      hpRoll.heading = Cesium.Math.toRadians(90.0)
      var orientation = Cesium.Transforms.headingPitchRollQuaternion(position, hpRoll)
      // 小车状态标志
      let flag = {
        moveUp: false,
        moveDown: false,
        moveLeft: false,
        moveRight: false,
      }
      // 添加模型
      let woman = viewer.entities.add({
        id: 'woman',
        position: new Cesium.CallbackProperty(getPositin, false),
        // 根据所提供的速度计算点
        orientation: new Cesium.CallbackProperty(getOrientation, false),
        model: {
          uri: '/static/model/walking/scene.gltf',
          runAnimations: new Cesium.CallbackProperty(getRun, false),
          scale: 0.012,
          // 贴地
          // heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
        },
      })

      // 根据键盘按键返回标志
      function setFlagStatus(key, value) {
        switch (key.keyCode) {
          case 37:
            // 左
            flag.moveLeft = value
            break
          case 38:
            // 上
            flag.moveUp = value
            break
          case 39:
            // 右
            flag.moveRight = value
            break
          case 40:
            flag.moveDown = value
            // 下
            break
        }
      }
      // 小车状态，停下时false，开始运动后都是true。
      var run = false
      document.addEventListener('keydown', (e) => {
        setFlagStatus(e, true)
        if (e.which === 40 || e.which === 39 || e.which === 38 || e.which === 37) {
          if (!run) {
            run = true
          }
        }
      })

      document.addEventListener('keyup', (e) => {
        setFlagStatus(e, false)
        if (e.which === 40 || e.which === 39 || e.which === 38 || e.which === 37) {
          if (flag.moveUp | flag.moveDown | flag.moveLeft | flag.moveRight) {
            return
          } else {
            run = false
          }
        }
      })
      var count = 0
      viewer.clock.onTick.addEventListener((clock) => {
        if (flag.moveUp) {
          if (flag.moveLeft) {
            hpRoll.heading -= radian
            count += 2
          }
          if (flag.moveRight) {
            hpRoll.heading += radian
            count -= 2
          }
          moveCar(1)
        } else if (flag.moveDown) {
          if (flag.moveLeft) {
            hpRoll.heading -= radian
            count += 2
          }
          if (flag.moveRight) {
            hpRoll.heading += radian
            count -= 2
          }
          moveCar(-1)
        } else {
          if (flag.moveLeft) {
            hpRoll.heading -= radian
            count += 2
            moveCar(0)
          }
          if (flag.moveRight) {
            hpRoll.heading += radian
            count -= 2
            moveCar(0)
          }
        }
      })
      // 移动小车
      function moveCar(isUP) {
        // 计算速度矩阵
        if (isUP === 1) {
          speedVector = Cesium.Cartesian3.multiplyByScalar(Cesium.Cartesian3.UNIT_X, speed, speedVector)
        } else if (isUP === -1) {
          speedVector = Cesium.Cartesian3.multiplyByScalar(Cesium.Cartesian3.UNIT_X, -speed, speedVector)
        } else {
          speedVector = Cesium.Cartesian3.multiplyByScalar(Cesium.Cartesian3.UNIT_X, 0, speedVector)
        }

        // 根据速度计算出下一个位置的坐标 north south east west
        let fixedFrameTransforms = Cesium.Transforms.localFrameToFixedFrameGenerator('east', 'north')
        let modelMatrix = Cesium.Transforms.headingPitchRollToFixedFrame(
          position,
          hpRoll,
          Cesium.Ellipsoid.WGS84,
          fixedFrameTransforms
        )
        position = Cesium.Matrix4.multiplyByPoint(modelMatrix, speedVector, position)
        //计算镜头设置的位置
        var cartesian3 = new Cesium.Cartesian3(position.x, position.y, position.z)
        var cartographic = scene.globe.ellipsoid.cartesianToCartographic(cartesian3)
        var lng =
          Cesium.Math.toDegrees(cartographic.longitude) -
          0.00001852398509 * 4 * Math.cos(((270 + count) * 2 * Math.PI) / 360)
        var lat =
          Cesium.Math.toDegrees(cartographic.latitude) -
          0.00001852398509 * 4 * Math.sin(((270 + count) * 2 * Math.PI) / 360)
        var alt = cartographic.height + 5
        // // 获取指定经纬度的高程
        // var toH=new Cesium.Cartographic.fromDegrees(lng,lat)
        // // var h = viewer.scene.globe.getHeight(toH)
        // var h2 = viewer.scene.sampleHeight(toH)
        // console.log(h2)
        //设置镜头
        viewer.camera.setView({
          destination: Cesium.Cartesian3.fromDegrees(lng, lat, alt),
          orientation: {
            // 指向  镜头随小车变化角度
            heading: hpRoll.heading + Cesium.Math.toRadians(90.0),
            // 视角固定
            pitch: Cesium.Math.toRadians(-15.0),
            roll: 0.0,
          },
        })
      }
      function getPositin() {
        return position
      }
      function getOrientation() {
        return Cesium.Transforms.headingPitchRollQuaternion(position, hpRoll)
      }
      function getRun() {
        return run
      }
      this.hideCar = 3
    },
    // 全屏
    screen() {
      screenfull.toggle()
    },
    // 控制站点和路线显示隐藏
    changeLine() {
      viewer.entities.show = !viewer.entities.show
      this.line_bool = !this.line_bool
      this.copyIndex = undefined
    },
    //飞行暂停
    pauseFly() {
      this.copyIndex = this.index
      this.index = this.drowallStops.length + 1
    },
    // 飞行停止
    stopFly() {
      this.index = this.drowallStops.length + 1
      this.copyIndex = undefined
    },
    startFly() {
      this.toStartFly()
    },
    // 添加站点
    addPlace() {
      var Stop = {}
      var position = viewer.scene.camera.position
      //参数传入站点变量
      Stop.heading = viewer.scene.camera.heading
      Stop.pitch = viewer.scene.camera.pitch
      Stop.roll = viewer.scene.camera.roll
      Stop.time = 10
      //传入飞行站点数组
      this.allStops.push(Stop)
      this.$message.success('设置站点成功')
      // console.log(this.allStops)
      //显示飞行路线
      var drowStop = {}
      var cartographic = Cesium.Cartographic.fromCartesian(position)
      drowStop.longitude = Cesium.Math.toDegrees(cartographic.longitude)
      drowStop.latitude = Cesium.Math.toDegrees(cartographic.latitude)
      drowStop.height = cartographic.height
      // console.log(Stop)

      this.drowallStops.push(drowStop)

      var length = this.drowallStops.length
      // 飞行路线和飞行站点
      if (this.line_bool) {
        if (this.drowallStops.length > 1) {
          // 实体路线
          viewer.entities.add({
            id: this.drowallStops.length + 1000,
            name: this.drowallStops.length + 1000,
            polyline: {
              positions: Cesium.Cartesian3.fromDegreesArrayHeights([
                this.drowallStops[length - 2].longitude,
                this.drowallStops[length - 2].latitude,
                this.drowallStops[length - 2].height,
                this.drowallStops[length - 1].longitude,
                this.drowallStops[length - 1].latitude,
                this.drowallStops[length - 1].height,
              ]),
              width: 5,
              material: Cesium.Color.BLUE,
            },
          })
        }
        //站点地标
        viewer.entities.add({
          position: Cesium.Cartesian3.fromDegrees(
            this.drowallStops[length - 1].longitude,
            this.drowallStops[length - 1].latitude,
            this.drowallStops[length - 1].height
          ),
          box: {
            dimensions: new Cesium.Cartesian3(0.5, 0.5, 1.0),
            material: Cesium.Color.WHITE,
          },
          name: this.drowallStops.length + 1000000,
          id: this.drowallStops.length + 1000000,
        })
      }

      //如果关闭显示了站点和飞行路线，添加的新站点和飞行路线将先不显示
      if (!this.line_bool) {
        if (this.drowallStops.length > 1) {
          viewer.entities.add({
            id: this.drowallStops.length + 1000,
            name: this.drowallStops.length + 1000,
            show: false,
            polyline: {
              positions: Cesium.Cartesian3.fromDegreesArrayHeights([
                this.drowallStops[length - 2].longitude,
                this.drowallStops[length - 2].latitude,
                this.drowallStops[length - 2].height,
                this.drowallStops[length - 1].longitude,
                this.drowallStops[length - 1].latitude,
                this.drowallStops[length - 1].height,
              ]),
              width: 5,
              material: Cesium.Color.BLUE,
            },
          })
        }
        viewer.entities.add({
          position: Cesium.Cartesian3.fromDegrees(
            this.drowallStops[length - 1].longitude,
            this.drowallStops[length - 1].latitude,
            this.drowallStops[length - 1].height
          ),
          box: {
            dimensions: new Cesium.Cartesian3(0.5, 0.5, 1.0),
            material: Cesium.Color.WHITE,
          },
          name: this.drowallStops.length + 1000000,
          id: this.drowallStops.length + 1000000,
          show: false,
        })
      }
    },
    // 清除站点
    cleanPlace() {
      this.allStops = []
      this.drowallStops = []
      viewer.entities._entities._array.forEach((res) => {
        if (res.id >= 1000) {
          viewer.entities.removeById(res.id)
        }
      })
    },
    myunchoosed() {
      window.earth.forEach((res) => {
        res.visible = true
      })
    },
    //展开
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys
      // this.autoExpandParent = false;
    },
    //选中
    onCheck(checkedKeys, e) {
      this.checkedKeys = checkedKeys
      this.myunchoosed()
      checkedKeys.forEach((res) => {
        window.earth.forEach((res1) => {
          if (res1.name.indexOf(res) > -1) {
            res1.visible = false
          }
        })
      })
    },
    //点击
    onSelect(selectedKeys, info) {
      this.selectedKeys = selectedKeys
    },
  },
  mounted() {
    //隐藏底部logo
    viewer._cesiumWidget._creditContainer.style.display = 'none'
    //显示帧数
    viewer.scene.debugShowFramesPerSecond = true
    // 碰撞检测-好像没有用
    viewer.scene.screenSpaceCameraController.enableCollisionDetection = true
    // viewer.scene.requestRenderMode=true;

    var promise = viewer.scene.open(window._CONFIG['TestAPP'])

    Cesium.when(promise, (layers) => {
      
      var listlayers = layers
      window.earth = layers
      console.log(layers)
      let layer = scene.layers.find(1)
      listlayers.forEach((res, i) => {
        //  修改了图层点击效果
        res.selectedColor=Cesium.Color.CYAN;
        // res.selectColorType=Cesium.SelectColorType.SILHOUETTE;
        res.selectColorType=Cesium.SelectColorType.ALWAYS_SHOW_SILHOUETTE;
        
        var layername = res.name.split('@')
        tcObj = {
          title: layername[1],
          key: layername[1],
          children: [],
        }

        // 数组不为空
        if (myChildren.length != 0) {
          // 判断是否重复
          var aa = myChildren.findIndex((item) => item.title === layername[1])
          if (aa == -1) {
            myChildren.push(tcObj)
          }
        } else {
          myChildren.push(tcObj)
        }
      })
      listlayers.forEach((res, i) => {
        var layername1 = res.name.split('@')
        //判断是否存在
        var aa = myChildren.findIndex((item) => item.title === layername1[1])
        tcObj = {
          title: layername1[0],
          key: layername1[0],
          id: res.id,
        }
        myChildren[aa].children.push(tcObj)
      })
    })
    this.treeData[0].children = myChildren

    // 叠加天地图
    var imageryLayers = viewer.imageryLayers
    // 初始化天地图全球中文注记服务，并添加至矢量图层
    var labelImagery = new Cesium.TiandituImageryProvider({
      mapStyle: Cesium.TiandituMapsStyle.VEC_C, //VEC_C矢量地图
      token: '9a070d5592c8fcc4fa1ef70a49723f68',
    })
    var CIA = new Cesium.TiandituImageryProvider({
      mapStyle: Cesium.TiandituMapsStyle.CIA_C, //VEC_C矢量地图cva_c
      token: '9a070d5592c8fcc4fa1ef70a49723f68',
    })

    imageryLayers.addImageryProvider(labelImagery)
    imageryLayers.addImageryProvider(CIA)

    // var highlighted = {
    //   feature: undefined,
    //   originalColor: new Cesium.Color(),
    // };
    //设置鼠标左键单击回调事件
    var handler = new Cesium.ScreenSpaceEventHandler(scene.canvas)
    handler.setInputAction(function (e) {
      //获取点击位置笛卡尔坐标
      var position = scene.pickPosition(e.position)
      //将笛卡尔坐标转化为经纬度坐标
      var cartographic = Cesium.Cartographic.fromCartesian(position)
      // console.log(cartographic)
      var longitude = Cesium.Math.toDegrees(cartographic.longitude)
      var latitude = Cesium.Math.toDegrees(cartographic.latitude)
      var height = cartographic.height
      if (height < 0) {
        height = 0
      }
      // 将坐标写入html
      createDescription(Cesium, [longitude, latitude, height])
      // 选中图层
      let selectlayer = viewer.scene.layers.getSelectedLayer()
      console.log(selectlayer)
      if(selectlayer){
        createBubble([longitude, latitude, height],selectlayer)
      }
      
      //弹窗随屏幕移动而移动
      var infoboxContainer = document.getElementById('bubble')
      scene.postRender.addEventListener(function () {
        // 每一帧都去计算气泡的正确位置
        if (position) {
          var canvasHeight = scene.canvas.height
          var windowPosition = new Cesium.Cartesian2()
          Cesium.SceneTransforms.wgs84ToWindowCoordinates(scene, position, windowPosition)
          infoboxContainer.style.bottom = canvasHeight - windowPosition.y + 45 + 'px'
          infoboxContainer.style.left = windowPosition.x - 70 + 'px'
          infoboxContainer.style.visibility = 'visible'
        }
      })
       pointDraged = viewer.scene.pick(e.position);
       console.log(pointDraged)
      
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK)

    //将坐标写入HTML
    function createDescription(Cesium, properties) {
      var simpleStyleIdentifiers = ['经度', '纬度', '高度']
      let html = ''
      // console.log(properties)
      for (var key in properties) {
        if (properties.hasOwnProperty(key)) {
          if (simpleStyleIdentifiers.indexOf(key) !== -1) {
            continue
          }
          var value = properties[key]
          if (Cesium.defined(value) && value !== '') {
            html += simpleStyleIdentifiers[key] + ':' + value + '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'
            // console.log(html)
          }
        }
      }
      document.getElementById('windowbox').innerHTML = html
    }
    var _this = this
    function createBubble(arr,obj) {
      _this.createBubble(arr,obj)
    }

    this.toStartFly = function () {
      var that = this
      if (this.copyIndex) {
        this.index = this.copyIndex
        this.copyIndex = undefined
        if (this.index < this.allStops.length) {
          scene.screenSpaceCameraController.enableRotate = false
          scene.screenSpaceCameraController.enableTranslate = false
          scene.screenSpaceCameraController.enableZoom = false
          scene.screenSpaceCameraController.enableTilt = false
          scene.screenSpaceCameraController.enableLook = false

          viewer.camera.setView({
            destination: new Cesium.Cartesian3.fromDegrees(
              this.drowallStops[this.index - 1].longitude,
              this.drowallStops[this.index - 1].latitude,
              this.drowallStops[this.index - 1].height
            ),
            orientation: {
              heading: this.allStops[this.index - 1].heading,
              pitch: this.allStops[this.index - 1].pitch,
              roll: this.allStops[this.index - 1].roll,
            },
          })
          fly()
          // l++
        }
      } else {
        this.index = 1
        if (this.index < this.allStops.length) {
          scene.screenSpaceCameraController.enableRotate = false
          scene.screenSpaceCameraController.enableTranslate = false
          scene.screenSpaceCameraController.enableZoom = false
          scene.screenSpaceCameraController.enableTilt = false
          scene.screenSpaceCameraController.enableLook = false

          viewer.camera.setView({
            destination: new Cesium.Cartesian3.fromDegrees(
              this.drowallStops[0].longitude,
              this.drowallStops[0].latitude,
              this.drowallStops[0].height
            ),
            orientation: {
              heading: this.allStops[0].heading,
              pitch: this.allStops[0].pitch,
              roll: this.allStops[0].roll,
            },
          })
          fly()
          // l++
        }
      }

      function fly() {
        if (that.index >= that.drowallStops.length) {
          scene.screenSpaceCameraController.enableRotate = true
          scene.screenSpaceCameraController.enableTranslate = true
          scene.screenSpaceCameraController.enableZoom = true
          scene.screenSpaceCameraController.enableTilt = true
          scene.screenSpaceCameraController.enableLook = true
        } else {
          let l = that.index
          // console.log(new Cesium.Cartesian3.fromDegrees(this.drowallStops[0].longitude, this.drowallStops[0].latitude, this.drowallStops[0].height))
          viewer.camera.flyTo({
            destination: new Cesium.Cartesian3.fromDegrees(
              that.drowallStops[l].longitude,
              that.drowallStops[l].latitude,
              that.drowallStops[l].height
            ), // 设置位置
            orientation: {
              heading: that.allStops[l].heading, // 方向
              pitch: that.allStops[l].pitch, // 倾斜角度
              roll: that.allStops[l].roll,
            },
            duration: 5, // 设置飞行持续时间，默认会根据距离来计算
            complete: function () {
              fly()
              // 到达位置后执行的回调函数
            },
          })
          that.index++
        }
      }
    }

  },
  created() {
    this.$root.$on('click', (val) => {
      if (this.isShow === val) {
        this.isShow = ''
      } else {
        this.isShow = val
      }
    })
  },
  watch: {
    isShow(n, o) {
      if (n != '2') {
        document.getElementById('viewer-panel').style.display = 'none'
      } else {
        document.getElementById('viewer-panel').style.display = 'block'
      }
    },
    checkedKeys(val, e) {},
  },
}
</script>

<style lang="less" scoped>
#map3 {
  margin-left: 75px;
  position: fixed;
  /* margin: 0 auto; */
  width: 96.5%;
  height: 100%;
}
.mytuceng {
  width: 200px;
}
#alllayers {
  margin-left: 8px;
  margin-top: 8px;
  padding: 16px;
  height: 100%;
  border-radius: 5px;
  position: fixed;
  z-index: 999;
  background: white;
  opacity: 0.85;
}
.mywindow {
  padding: 0px 8px;
  line-height: 20px;
  width: 100%;
  position: fixed;
  z-index: 999;
  background: #212121;
  opacity: 0.8;
  bottom: 0;
}
.myearth {
  bottom: 8px;
  right: 8px;
  display: inline-flex;
  text-align: center;
  padding: 8px;
  border-radius: 5px;
  position: fixed;
  z-index: 999;
  background: #212121;
}
.fly {
  position: fixed;
  z-index: 999;
  margin-top: 8px;
  margin-left: 8px;
  padding: 8px;
  background: #333131;
  border-radius: 5px;
  opacity: 0.8;
}
.button {
  border: 1px solid darkgray;
  background: rgb(0, 0, 0);
  margin: 8px;
  font-size: 14px;
  padding: 3px;
  border-radius: 3px;
  color: #fff;
}


// .bubble {
//   text-align: center;
//   z-index: 999;
//   text-align: center;
//   position: fixed;
//   padding: 15px;
//   margin: 0;
//   background: #fff;
//   max-width: 300px;
//   max-height: 200px;
// }

// .bubble:after {
//   content: '';
//   position: absolute;
//   // bottom: -50px;
//   left: 30%;
//   border-width: 0 20px 50px 0px;
//   border-style: solid;
//   border-color: transparent #fff;
//   display: block;
//   width: 0;
// }


// /* Alternating background colors */
// #tab tr:nth-child(even) {
//   background: rgb(223, 216, 232);
// }
// #tab tr:nth-child(odd) {
//   background: rgb(163, 30, 30);
// }

/*-------bubble------------------*/
.bubble {
    text-align:center;
    z-index: 999;
    position: fixed;
    padding: 15px;
    margin: 0;
    background: #fff;
    max-width : 330px;
    max-height: 200px;
}
.bubble float{
    right: 2%;
    top: 2%; 
}
.bubble:after {
    content: "";
    position: absolute;
    bottom: -50px;
    left: 50px;
    border-width: 0 20px 50px 0px;
    border-style: solid;
    border-color: transparent #fff;
    display: block;
    width: 0;
}
/* Border styles */
#tab thead, #tab tr {
    border-top-width: 1px;
    border-top-style: solid;
    border-top-color: rgb(211, 202, 221);
}
#tab {
    border-bottom-width: 1px;
    border-bottom-style: solid;
    border-bottom-color: rgb(211, 202, 221);
    height: 400px !important;
}

/* Padding and font style */
#tab td, #tab th {
    padding: 5px 10px !important;
    font-size: 12px !important;
    font-family: Verdana !important;
    color: rgb(95, 74, 121) !important;
    border: 1px solid rgb(193, 168, 223) !important;
}

/* Alternating background colors */
#tab tr:nth-child(even) {
    background: rgb(223, 216, 232) !important
}
#tab tr:nth-child(odd) {
    background: #FFF !important
}
.float{
    position: absolute;
    text-align: center;
    padding: 15px;
    margin: 0;
    background: #fff;
    max-width: 330px;
    max-height: 400px;
}
/*-------bubble  end------------------*/

</style>